package com.arpa.wms.service.impl;

import cn.hutool.core.util.IdUtil;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.entity.Shipment;
import com.arpa.ntocc.common.domain.vo.ShipmentVO;
import com.arpa.ntocc.common.mapper.ShipmentMapper;
import com.arpa.wms.cache.WarehouseShipmentCache;
import com.arpa.wms.domain.dto.WarehouseShipmentDTO;
import com.arpa.wms.domain.entity.WarehouseShipment;
import com.arpa.wms.domain.vo.WarehouseShipmentVO;
import com.arpa.wms.mapper.WarehouseShipmentMapper;
import com.arpa.wms.service.IWarehouseShipmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

import static com.arpa.wms.domain.consts.NumConst.NUM_ONE;

/**
 * <p>
 * 仓库 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2020-08-03
 */
@Service
@Log4j2
public class WarehouseShipmentServiceImpl extends ServiceImpl<WarehouseShipmentMapper, WarehouseShipment> implements IWarehouseShipmentService {


    private final WarehouseShipmentCache warehouseShipmentCache;

    @Resource
    private ShipmentMapper shipmentMapper;

    public WarehouseShipmentServiceImpl(
            WarehouseShipmentCache warehouseShipmentCache) {
        this.warehouseShipmentCache = warehouseShipmentCache;
    }


    /**
     * 查询列表
     *
     * @param warehouseShipmentDTO
     * @return
     */
    @Override
    public List<WarehouseShipmentVO> queryList(WarehouseShipmentDTO warehouseShipmentDTO) {
        //排序字段名需要驼峰转数据库下划线类型字段名
        if (StringUtils.isNotEmpty(warehouseShipmentDTO.getSortField())) {
            warehouseShipmentDTO.setSortField(CommonUtil.camel2Underline(warehouseShipmentDTO.getSortField()));
        }
        return baseMapper.queryList(warehouseShipmentDTO);
    }

    /**
     * 查询合计,包含总数
     *
     * @param warehouseDTO
     * @return
     */
    @Override
    public WarehouseShipmentVO queryListSum(WarehouseShipmentDTO warehouseDTO) {
        return baseMapper.queryListSum(warehouseDTO);
    }

    /**
     * 删除仓库货主绑定关系
     *
     * @param code
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByCode(String code) {
        baseMapper.deleteByCode(code);
        warehouseShipmentCache.flushCache(code);
    }


    /**
     * 保存货主确认
     *
     * @param codes         货主codes
     * @param warehouseCode 仓库code
     */
    @Override
    public void saveChoose(List<String> codes, List<Integer> useOms, String warehouseCode) {
        StringBuilder data = new StringBuilder();
        data.append("INSERT INTO `wms_warehouse_shipment`(`id`, `code`,`group_code`, `warehouse_code`, `shipment_code`, `is_use_oms`, `created_by`, `gmt_created`, `modified_by`, `gmt_modified`) values ");
        for (int i = 0; i < codes.size(); i++) {
            data.append(makeInsertValuesString(codes.get(i), warehouseCode, useOms.get(i)));
        }
        this.baseMapper.insertDataBySql(data.deleteCharAt(data.length() - NUM_ONE).toString());
        warehouseShipmentCache.flushCache(warehouseCode);
    }

    /**
     * 查询仓库可选择的货主信息
     *
     * @param warehouseShipmentDTO
     * @return
     */
    @Override
    public ShipmentVO queryShipmentListSum(WarehouseShipmentDTO warehouseShipmentDTO) {
        return baseMapper.queryShipmentListSum(warehouseShipmentDTO);
    }

    /**
     * 查询仓库可选货主的数量
     *
     * @param warehouseShipmentDTO
     * @return
     */
    @Override
    public List<ShipmentVO> queryShipmentList(WarehouseShipmentDTO warehouseShipmentDTO) {
        return baseMapper.queryShipmentList(warehouseShipmentDTO);
    }

    /**
     * 构建sql 添加语句
     */
    private StringBuilder makeInsertValuesString(final String shipmentCode, final String warehouseCode, final Integer useOms) {

        Shipment shipment = shipmentMapper.selectOne(new LambdaQueryWrapper<Shipment>().eq(Shipment::getPartyCode, shipmentCode).eq(Shipment::getAuthStatus, 3));
        if (null == shipment) {
            log.error("找不到货主【{}】信息", shipmentCode);
            throw new ServiceException("找不到货主【" + shipmentCode + "】信息");
        }

        StringBuilder data = new StringBuilder();
        data.append("(");
        //id
        data.append("default,");
        //code
        data.append("'").append(IdUtil.simpleUUID()).append("',");
        //group_code
        data.append("'").append(UserUtil.getBranchCode()).append("',");
        //warehouse_code
        data.append("'").append(warehouseCode).append("',");
        //shipment_code
        data.append("'").append(shipmentCode).append("',");
        // is_use_oms
        data.append(useOms).append(",");
        //created_by
        data.append("'").append(UserUtil.getCode()).append("',");
        //gmt_created
        data.append("'").append(LocalDateTime.now()).append("',");
        //modified_by
        data.append("'").append(UserUtil.getCode()).append("',");
        //gmt_modified
        data.append("'").append(LocalDateTime.now()).append("'");
        data.append("),");
        return data;
    }

    /**
     * 判断货主仓库是否绑定
     *
     * @param warehouseCode 仓库标识
     * @param shipmentCode  货主标识
     * @return true绑定，false未绑定
     */
    @Override
    public boolean isBind(String warehouseCode, String shipmentCode) {
        int count = count(new QueryWrapper<WarehouseShipment>().lambda().eq(WarehouseShipment::getShipmentCode, shipmentCode).eq(WarehouseShipment::getWarehouseCode, warehouseCode)
        .eq(WarehouseShipment::getGroupCode,UserUtil.getBranchCode()));
        return count > 0;
    }


    /**
     * 获取所有仓库货主绑定信息
     *
     * @return
     */
    @Override
    public List<WarehouseShipmentVO> getAll(String groupCode) {
        return baseMapper.getAll(groupCode);
    }

}
